/*
 * C Implementation: grib_iterator
 *
 * Description: 
 * how to use an iterator on lat/lon/values for GRIB messages
 * 如何在 GRIB 消息的纬度/经度/值上使用迭代器
 * 
 * codes_handle *h          - message handle. 在对消息起作用的所有 ecCodes 调用中是必需的
 * codes_iterator *iter     - iterator
 * 
 */

#include <stdio.h>
#include <stdlib.h>

#include "eccodes.h"


int sfx_grib_iterator()
{
    int err = 0;

    char* filename = "d:\\temp\\era5-levels-members.grib";

    FILE* in = fopen(filename, "rb");

    int n               = 0;
    codes_handle* h     = NULL;
    double missingValue = 1e+20;  // 缺失值
    // Loop on all the messages in a file.
    while ((h = codes_handle_new_from_file(NULL, in, PRODUCT_GRIB, &err)) != NULL) {
        //
        // Check of errors after reading a message.
        if (err != CODES_SUCCESS) CODES_CHECK(err, 0);

        // Set the double representing the missing value in the field. (设置表示字段中缺失值的双精度值。)
        // Choose a missingValue that does not correspond to any real value in the data array (选择一个与数据数组中任何实际值都不对应的缺失值)
        CODES_CHECK(codes_set_double(h, "missingValue", missingValue), 0);

        // A new iterator on lat/lon/values is created from the message handle h.
        codes_iterator* iter = codes_grib_iterator_new(h, 0, &err);

        n = 0;
        double lat, lon, value;
        // Loop on all the lat/lon/values.
        while (codes_grib_iterator_next(iter, &lat, &lon, &value)) {
            // You can now print lat and lon,
            /*
            printf("- %d - lat=%f lon=%f value=", n, lat, lon);
            if (value == missingValue) {
                printf("missing\n");
            }
            else {
                printf("%f\n", value);
            }
            */
            n++;
        }
        //

        // free memory.
        codes_grib_iterator_delete(iter);
        codes_handle_delete(h);
    }


    fclose(in);
    return 0;
}
